package com.bdqn.controller;

import com.bdqn.constant.Constant;
import com.bdqn.pojo.PageSupport;
import com.bdqn.pojo.SysRole;
import com.bdqn.pojo.SysUser;

import com.bdqn.service.SysUserService;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.List;

@Controller
@RequestMapping("/user")
public class SysUserController {
    private Logger logger = Logger.getLogger(SysUserController.class);

    @Resource
    private SysUserService sysUserService;

    //跳转到登录页面
    @RequestMapping("/toLogin")
    public String login(){
        logger.debug("跳转到登录页面");
        return "login";
    }

    //登录
    @PostMapping("/login")
    public String doLogin(@RequestParam String account, @RequestParam String password, HttpServletRequest request, HttpSession session){
        logger.debug("进入登录方法");
        System.out.println("账号：" + account + "\n密码：" + password);
        //调用Service方法，进行用户匹配
        SysUser sysUser = sysUserService.login(account,password);
        if (null != sysUser){
            //将登录用户放入session
            session.setAttribute(Constant.USER_SESSION,sysUser);
            //登录成功，重定向到/user/toMain接口
            return "redirect:/user/toMain";
        }else {
            //页面跳转（login.jsp）带出提示信息--转发
            request.setAttribute("error","用户名或密码不正确");
            //用户不存在，登录失败，跳转到登录页面
            return "login";
        }
    }

    //跳转到首页
    @RequestMapping("/toMain")
    public String main(HttpSession session){
        if (session.getAttribute(Constant.USER_SESSION) == null){
            //重定向到登录页面接口
            return "redirect:/user/toLogin";
        }
        return "frame";
    }

    //捕获异常信息，跳转到error页面
    @ExceptionHandler(value = {RuntimeException.class})
    public String handlerException(RuntimeException e, HttpServletRequest req){
        req.setAttribute("e",e);
        return "error";
    }

    //一个抛出异常的接口
    @RequestMapping("/exLogin")
    public String exLogin(@RequestParam String account,@RequestParam String password){
        SysUser user = sysUserService.login(account,password);
        if (null == user){
            throw new RuntimeException("用户名或者密码不正确！");
        }
        return "redirect:/user/toMain";
    }

    @GetMapping("/list")
    public String getUserList(Model model,String queryRealName,Integer queryRoleId,@RequestParam(defaultValue = "1") Integer pageIndex){
        List<SysUser> userList = null;
        try{
            //设置页面容量
            int pageSize = Constant.pageSize;
            //总数量(表)
            int totalCount = sysUserService.getUserCount(queryRealName,queryRoleId);
            //总页数
            PageSupport pages = new PageSupport();
            pages.setCurrentPageNo(pageIndex);
            pages.setPageSize(pageSize);
            pages.setTotalCount(totalCount);
            int totalPageCount = pages.getTotalPageCount();
            //控制首页和尾页
            if (pageIndex > totalPageCount){
                pageIndex = totalPageCount;
                throw new RuntimeException("页码不正确");
            }
            userList = sysUserService.getUserList(queryRealName,queryRoleId,pageIndex,pageSize);
            model.addAttribute("userList",userList);
            List<SysRole> roleList = null;
            model.addAttribute("roleList",roleList);
            model.addAttribute("queryRealName",queryRealName);
            model.addAttribute("queryRoleId",queryRoleId);
            model.addAttribute("page",pages);
        }catch (Exception e){
            e.printStackTrace();
            logger.error("用户列表接口访问失败");
            return "redirect:/user/toSysError";
        }
        return "sysUser/list";
    }
    //跳转到异常处理页面
    @RequestMapping(value = "/toSysError")
    public String sysError(){
        return "sysError";
    }

    //退出登录
    @RequestMapping("/logout")
    public String logout(){
        return "login";
    }

    //跳转到添加用户页面
    @RequestMapping("/toAdd")
    public String toAdd(){
        return "sysUser/add";
    }

    @PostMapping("/add")
    public String add(@Valid SysUser sysUser, BindingResult bindingResult,HttpSession session){
        if (bindingResult.hasErrors()){
            logger.debug("添加用户失败");
            return "sysUser/add";
        }
        sysUser.setCreatedUserId(((SysUser)session.getAttribute(Constant.USER_SESSION)).getId());
        if (sysUserService.add(sysUser)){
            return "redirect:/user/list";
        }
        return "sysUser/add";
    }
    //查询用户详情
    @GetMapping("/view/{id}")
    public String view(@PathVariable String id,Model model){
        logger.debug("根据id查询用户详情"+id);
        SysUser sysUser=sysUserService.getUserById(id);
        model.addAttribute(sysUser);
        return "sysUser/view";
    }
    //去修改
    @GetMapping("/toUpdate")
    public String toUpdate(@RequestParam String uid,Model model){
        logger.debug("跳转到修改用户信息页面");
        SysUser sysUser=sysUserService.getUserById(uid);
        model.addAttribute(sysUser);
        return "sysUser/update";
    }

    //修改用户信息
    @PostMapping("/update")
    public String update(SysUser sysUser,HttpSession session){
        logger.debug("修改用户信息");
        sysUser.setUpdatedUserId(((SysUser)session.getAttribute(Constant.USER_SESSION)).getId());
        if (sysUserService.update(sysUser)){
            return "redirect:/user/list";
        }
        return "sysUser/update";
    }
    //跳转到添加用户页面
    @GetMapping("add")
    public String toAdd(@ModelAttribute("sysUser")SysUser sysUser){
        return "sysUser/add";
    }
}
